package com.example.lenovo.asia5b.util;

import android.content.Context;
import android.content.SharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import app.MyApplication;
import fay.frame.fast.FHelper;
import fay.frame.fast.callback.AjaxCallback;
import fay.frame.fast.callback.AjaxStatus;
import fay.frame.service.S;
import fay.frame.tools.Debug;

public class JsonTools {
	private static int deviceTypeAndroid=2;

	/**
	 * 调用接口 返回reInfos
	 *
	 * @param iCallBack
	 * @param url
	 * @param formMap
	 * @param action
	 */
	public static void getJsonInfo(final ICallBack iCallBack, String url,
								   Map<String, String> formMap, final int action) {
		Map<String, String> map = new HashMap<String, String>();

		if (null != formMap) {
			for (String key : formMap.keySet()) {
				map.put(key, HtmlUtil.urlEncoder(formMap.get(key)));
			}
		}
		S.getF().ajax(url, map, JSONObject.class,
				new AjaxCallback<JSONObject>() {
					@Override
					public void callback(String url, JSONObject json,
										 AjaxStatus status) {
						try {
							JSONObject result = FHelper.getData(url, json,
									status);
							Object obj = null;
							if (null != result) {
								obj = result.get("reInfos");
							}
							iCallBack.logicFinish(obj, action);
						} catch (JSONException e) {
							Debug.outErr(e);
						}

					}
				});
	}

	/**
	 * 调用接口 返回所有
	 * @param iCallBack
	 * @param url
	 * @param formMap
	 * @param action
	 */
	public static void getJsonAll( final ICallBack iCallBack,  String url, Map<String, String> formMap, final int action) {
		SharedPreferences languagePre = MyApplication.getContextObject().getSharedPreferences("language_choice", Context.MODE_PRIVATE);

		if (null == formMap) {
			formMap = new HashMap<String, String>();
		}
		int lang_id = languagePre.getInt("id", 1) + 1;
		formMap.put("lang_id", lang_id + "");
		formMap.put("user_alias", MyApplication.registrationId);
		formMap.put("deviceType", deviceTypeAndroid+"");
		JsonTools2.GetHttps(iCallBack,url,formMap,action);
		/*final Map paramMap = formMap;
		Handler handler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				try {

				}catch (Exception e){
					e.printStackTrace();
				}
			};
		};
		Message msg = new Message();
		msg.what=0;
		handler.sendMessage(msg);*/
	}

	/**
	 * 调用接口 返回所有
	 * @param iCallBack
	 * @param url
	 * @param formMap
	 * @param action
	 */
	public static void getJSONArrayAll( final ICallBack iCallBack, String url,Map<String, String> formMap, final int action) {
		Map<String, String> map = new HashMap<>();
		if (null != formMap) {
			for (String key : formMap.keySet()) {
				System.out.println("key= " + key + " and value= " + map.get(key));
				map.put(key, HtmlUtil.urlEncoder(formMap.get(key)));
			}
		}
		S.getF().ajax(url, map, JSONArray.class,
				new AjaxCallback<JSONArray>() {
					@Override
					public void callback(String url, JSONArray json, AjaxStatus status) {
						iCallBack.logicFinish(json, action);
						System.out.println("result:            " + json);
					}
				});
	}

	public static void getJsonAll2(final ICallBack iCallBack, String url,
								   Map<String, String> formMap, final int action) {
//		Map<String, String> map = FHelper.getParams(url);
		Map<String, String> map = new HashMap<>();
		if (null != formMap) {
			for (String key : formMap.keySet()) {
				System.out.println("key= " + key + " and value= "
						+ map.get(key));
				map.put(key, formMap.get(key));
			}
		}
		S.getF().ajax(url, map, JSONObject.class,
				new AjaxCallback<JSONObject>() {
					@Override
					public void callback(String url, JSONObject json,
										 AjaxStatus status) {
						iCallBack.logicFinish(json, action);
						System.out.println("result:            " + json);
					}
				});
	}

	public static void getJson24H(final ICallBack iCallBack, String url,
								  Map<String, String> formMap, final int action) {
//		Map<String, String> map = FHelper.getParams(url);
//		map.put("sessionID",SharedPreferencesUtils.getString(SharedPreferences_Parameter.LC_SESSIONID,""));
		Map<String, String> map = new HashMap<>();
		if (null != formMap) {
			for (String key : formMap.keySet()) {
				System.out.println("key= " + key + " and value= "
						+ map.get(key));
				map.put(key, HtmlUtil.urlEncoder(formMap.get(key)));
			}
		}
		//S.getF().CACHE_TIME_24H,
		S.getF().ajax(url, map, JSONObject.class, S.getF().CACHE_TIME_24H,
				new AjaxCallback<JSONObject>() {
					@Override
					public void callback(String url, JSONObject json,
										 AjaxStatus status) {
						try {
							JSONObject result = FHelper.getData(url, json,
									status);
							Object obj = null;
							if (null != result) {
								obj = result.get("reInfos");
							}
							iCallBack.logicFinish(obj, action);
						} catch (JSONException e) {
							Debug.outErr(e);
						}
					}
				});
	}

	public static void getJson24H2(final ICallBack iCallBack, String url,
								   Map<String, String> formMap, final int action) {
//		Map<String, String> map = FHelper.getParams(url);
		Map<String, String> map = new HashMap<>();
		if (null != formMap) {
			for (String key : formMap.keySet()) {
				System.out.println("key= " + key + " and value= "
						+ map.get(key));
				map.put(key, HtmlUtil.urlEncoder(formMap.get(key)));
			}
		}
		S.getF().ajax(url, map, JSONObject.class, S.getF().CACHE_TIME_24H,
				new AjaxCallback<JSONObject>() {
					@Override
					public void callback(String url, JSONObject json,
										 AjaxStatus status) {
						iCallBack.logicFinish(json, action);
					}
				});
	}

	public static void download(final ICallBack iCallBack, String url,
								File file, final int action) {
		S.getF().download(url, file, new AjaxCallback<File>() {
			@Override
			public void callback(String url, File file, AjaxStatus status) {
				iCallBack.logicFinish(file, action);
				// 文件下载完毕的处理
			}

		});
	}

	// public static void download2( final ICallBack iCallBack,String url,File
	// file,final int action){
	// S.getF().progress(S.getF().id(R.id.progress).getProgressBar()).download(url,
	// file, AjaxCallback<File>() {
	// @Override
	// public void callback(String url2, File file2,AjaxStatus status) {
	//
	// //文件下载完毕的处理
	//
	// }
	//
	// });
	// }

	public static void upload(final ICallBack iCallBack, String url, File file,
							  String method) {
		// String url = "http://www.test.com/upLoadFile.do";
		Map<String, Object> params = new HashMap<String, Object>();
		byte[] data = new byte[1000];
		params.put("source", data);
		params.put("sessionID", SharedPreferencesUtils.getString(SharedPreferences_Parameter.LC_SESSIONID,""));
		// File file = new File("test.png");

		params.put("source", file);

		S.getF().ajax(url, params, JSONObject.class, iCallBack, method);// method为上传成功后,调用的方法
	}

	public static List<Map<String, String>> arrayToLsit(JSONArray json) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		if (null != json && json.length() > 0) {
			try {
				for (int i = 0; i < json.length(); i++) {
					String key = null;
					JSONObject JsonObjectInside = (JSONObject) json.get(i);
					@SuppressWarnings("unchecked")
					Iterator<String> iterInside = JsonObjectInside.keys();
					Map<String, String> map = new HashMap<String, String>();
					while (iterInside.hasNext()) {
						key = iterInside.next();
						map.put(key, JsonObjectInside.getString(key));
					}
					list.add(map);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	/**
	 *
	 * 从JSONArray中抽取两个元素的值.一个作为KEY,一个作为VALUE. 以便解决对JSONArray中某两个关联元素的频繁检索</p>
	 * 比如JSONArray是大量人员信息对象. 现想查询姓名及性别. 则可设置姓名为KEY,性别为VALUE. 调用此方法形成检索Map.
	 * KEY具有唯一性
	 */
	public static HashMap<String, String> JsonArray2Map_twoElement(
			JSONArray jsonArr, HashMap<String, String> hashMap,
			String jsonKey4MapKey, String jsonKey4MapValue) {
		if (hashMap == null) {
			hashMap = new HashMap<String, String>();
		}
		try {
			for (int i = 0; i < jsonArr.length(); i++) {
				JSONObject jsonObject = jsonArr.getJSONObject(i);
				hashMap.put(jsonObject.getString(jsonKey4MapKey),
						jsonObject.getString(jsonKey4MapValue));
			}
		} catch (JSONException e) {
			Debug.out("JsonArray2Map_twoElement " + e);
		}
		return hashMap;
	}

	public static HashMap<String, String> JsonArray2Map_twoElement(
			JSONObject json, String key, String value) {
		return JsonArray2Map_twoElement(json, null, key);
	}

	public static Map<String, String> jsonToMap(JSONObject json) {
		Map<String, String> map = new HashMap<String, String>();
		if (null != json && json.length() > 0) {
			try {
				String key = null;
				@SuppressWarnings("unchecked")
				Iterator<String> iterInside = json.keys();
				while (iterInside.hasNext()) {
					key = iterInside.next();
					map.put(key, json.getString(key));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

	public static List<Map<String, String>> stringToLsit(String data) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		if (null != data && !"".equals(data)) {
			JSONArray json;
			try {
				json = new JSONArray(data);
				for (int i = 0; i < json.length(); i++) {
					String key = null;
					JSONObject JsonObjectInside = (JSONObject) json.get(i);
					@SuppressWarnings("unchecked")
					Iterator<String> iterInside = JsonObjectInside.keys();
					Map<String, String> map = new HashMap<String, String>();
					while (iterInside.hasNext()) {
						key = iterInside.next();
						map.put(key, JsonObjectInside.getString(key));
					}
					list.add(map);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return list;
	}

	public static Map<String, Object> stringToMap(String data) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null != data && !"".equals(data)) {
			JSONObject json;
			try {
				json = new JSONObject(data);
				if (null != json) {
					String key = null;
					@SuppressWarnings("unchecked")
					Iterator<String> iterInside = json.keys();
					while (iterInside.hasNext()) {
						key = iterInside.next();
						map.put(key, json.get(key));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		return map;
	}

	public static Map<String, String> stringToMap2(String data) {
		Map<String, String> map = new HashMap<String, String>();
		if (null != data && !"".equals(data)) {
			JSONObject json;
			try {
				json = new JSONObject(data);
				if (null != json) {
					String key = null;
					@SuppressWarnings("unchecked")
					Iterator<String> iterInside = json.keys();
					while (iterInside.hasNext()) {
						key = iterInside.next();
						map.put(key, json.getString(key));
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}
		return map;
	}
}
